/**
 * @author Dennis
 * @description 主要处理项目中的 省市区直辖市选择，以及参数 callback
 * @params { options } Object
 */
import React, { memo, useState } from 'react';
import { Select, Space } from 'antd';
const allArea = require('./lib/pca-code.json');

export interface baseList {
  value: string;
  label: string;
  children: baseList[];
}

export interface baseViewArea {
  type: "city" | ""
}

const ViewArea: React.FC<baseViewArea> = () => {
  const [ cityList, setCityList ] = useState([]);
  const [ areaList, setAreaList ] = useState([]);
  const [ cityValue, setCityValue ] = useState<string|undefined>(undefined);
  const [ areaValue, setAreaValue ] = useState<string|undefined>(undefined);
  const [ list, SetList ] = useState<{ value: string, label: string }[]>([]);

  const handleChange = (val: string) => {
    const { value, label, children } = allArea.find((k:baseList) => k.value === val);
    setAreaList([]);
    setCityList([]);
    setCityList(children);
    setCityValue(undefined);
    setAreaValue(undefined);
    SetList([{ value, label }]);
  }

  const handleChangeCity = (val: string) => {
    const { value, label, children }: any = cityList.find((k: baseList) => k.value === val);
    SetList(list.concat([{ value, label }]));
    setCityValue(val);
    setAreaList(children);
  }

  const handleChangeArea = (val: string) => {
    const { label, value }: any = areaList.find((k: baseList) => k.value === val);
    setAreaValue(val);
    SetList(list.concat([{ value, label }]));
  }

  return (
    <Space wrap>
      <Select
        placeholder="请选择省份"
        style={{ width: 200 }}
        onChange={handleChange}
        options={allArea}
      />
      <Select
        placeholder="请选择城市"
        style={{ width: 200 }}
        onChange={handleChangeCity}
        options={cityList}
        value={cityValue}
        disabled={cityList.length === 0}
      />
      <Select
        placeholder="请选择区域"
        value={areaValue}
        style={{ width: 200 }}
        onChange={handleChangeArea}
        options={areaList}
        disabled={areaList.length === 0}
      />
    </Space>
  )
}

export default memo(ViewArea);
